<template>
  <view class="container">
    <!-- 查询和新增按钮 -->
    <view class="header">
      <uni-button type="primary" size="mini" @click="openAddPopup">新增单位</uni-button>
      <uni-search-bar v-model="searchTerm" @confirm="filterUnits" @clear="filterUnits" placeholder="搜索单位" class="search-bar"></uni-search-bar>
      <uni-button type="default" size="mini" @click="filterUnits">搜索</uni-button>
    </view>

    <!-- 商品单位列表 -->
    <view class="main-content">
      <uni-table :border="true">
        <uni-tr>
          <uni-th align="center">单位名称</uni-th>
          <uni-th align="center">排序</uni-th>
          <uni-th align="center">单位类别</uni-th>
          <uni-th align="center">操作</uni-th>
        </uni-tr>
        <uni-tr v-for="unit in filteredUnits" :key="unit.id">
          <uni-td align="center">{{ unit.name }}</uni-td>
          <uni-td align="center">{{ unit.sort_order }}</uni-td>
          <uni-td align="center">{{ unit.category }}</uni-td>
          <uni-td align="center">
            <uni-button type="default" size="mini" @click="openEditPopup(unit)">编辑</uni-button>
            <uni-button type="error" size="mini" @click="openDeletePopup(unit)">删除</uni-button>
          </uni-td>
        </uni-tr>
      </uni-table>
    </view>

    <!-- 新增/编辑单位弹窗 -->
    <uni-popup ref="editPopup" type="center">
      <view class="popup-container">
        <h3>{{ currentUnit.id ? '编辑单位' : '新增单位' }}</h3>
        <view class="form-row">
          <label>单位名称：</label>
          <input v-model="currentUnit.name" placeholder="请输入单位名称" class="input-field"/>
        </view>
        <view class="form-row">
          <label>排序：</label>
          <input type="number" v-model.number="currentUnit.sort_order" placeholder="输入排序" class="input-field"/>
        </view>
        <view class="form-row">
          <label>单位类别：</label>
          <input v-model="currentUnit.category" placeholder="请输入单位类别" class="input-field"/>
        </view>
        <view class="button-group">
          <uni-button type="primary" size="small" @click="saveUnit" style="width: 100%;">保存</uni-button>
          <uni-button type="default" size="small" @click="closePopup" style="width: 100%;">取消</uni-button>
        </view>
      </view>
    </uni-popup>

    <!-- 删除确认弹窗 -->
    <uni-popup ref="deletePopup" type="center">
      <view class="popup-container">
        <h3>确认删除</h3>
        <text>确定要删除 "{{ currentUnit.name }}" 吗？</text>
        <view class="button-group">
          <uni-button type="error" size="small" @click="confirmDelete">删除</uni-button>
          <uni-button type="default" size="small" @click="closePopup">取消</uni-button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      searchTerm: '',
      units: [],
      filteredUnits: [],
      currentUnit: {
        id: null,
        name: '',
        sort_order: '',
        category: ''
      },
      userInfo: {},
      mainAccountId: null
    };
  },
  methods: {
    filterUnits() {
      if (this.searchTerm) {
        this.filteredUnits = this.units.filter(unit => 
          unit.name.includes(this.searchTerm) ||
          unit.category.includes(this.searchTerm)
        );
      } else {
        this.filteredUnits = this.units;
      }
    },
    async fetchUnits() {
      const res = await this.$myRuquest({
        url: '/index/plugin.users/getUnits',
        method: 'GET',
        data: {
          main_account_id: this.mainAccountId
        }
      });
      if (res.data.code === 200) {
        this.units = res.data.data;
        this.filterUnits();
      } else {
        uni.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 2000
        });
      }
    },
    openAddPopup() {
      this.currentUnit = { id: null, name: '', sort_order: '', category: '' };
      this.$refs.editPopup.open();
    },
    openEditPopup(unit) {
      this.currentUnit = { ...unit };
      this.$refs.editPopup.open();
    },
    closePopup() {
      this.$refs.editPopup.close();
      this.$refs.deletePopup.close();
    },
    async saveUnit() {
      const res = await this.$myRuquest({
        url: '/index/plugin.users/saveUnit',
        method: 'POST',
        data: {
          ...this.currentUnit,
          main_account_id: this.mainAccountId
        }
      });
      if (res.data.code === 200) {
        uni.showToast({
          title: '操作成功',
          icon: 'success',
          duration: 2000
        });
        this.fetchUnits();
        this.closePopup();
      } else {
        uni.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 2000
        });
      }
    },
    openDeletePopup(unit) {
      this.currentUnit = { ...unit };
      this.$refs.deletePopup.open();
    },
    async confirmDelete() {
      const res = await this.$myRuquest({
        url: '/index/plugin.users/deleteUnit',
        method: 'POST',
        data: {
          id: this.currentUnit.id,
          main_account_id: this.mainAccountId
        }
      });
      if (res.data.code === 200) {
        uni.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 2000
        });
        this.fetchUnits();
        this.closePopup();
      } else {
        uni.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 2000
        });
      }
    },
    checkLoginStatus() {
      const token = uni.getStorageSync('token');
      if (token) {
        this.userInfo = JSON.parse(uni.getStorageSync('userInfo'));
        this.mainAccountId = this.userInfo.user_id;
      } else {
        this.userInfo = {};
        this.$router.push('/pages/login/login');
      }
    }
  },
  mounted() {
    this.checkLoginStatus();
    this.fetchUnits();
  }
};
</script>

<style scoped>
.container {
  padding: 20px;
  background-color: #fff;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  background-color: #fff;
  margin-top: 10px;
  margin-bottom: 10px;
  border-radius: 5px;
}

.search-bar {
  flex: 1;
  margin: 0 10px;
}

.main-content {
  text-align: center;
  background-color: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

h3 {
  margin-bottom: 20px;
  text-align: center;
  color: #333;
}

.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

label {
  width: 80px;
  color: #666;
  margin-right: 10px;
}

.input-field {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  outline: none;
}

.popup-container {
  width: 80%;
  max-width: 500px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.button-group {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

uni-button {
  margin-left: 10px;
}
</style>
